package com.jy.oms.framework.asyn.task.web;

import com.jy.oms.framework.thread.ThreadPoolPageController;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scripting.support.ResourceScriptSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 页面跳转
 *
 * @author liuquan
 */
@WebServlet("/taskQueue/page")
public class TaskQueuePageServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(ThreadPoolPageController.class);

    private LazyInitializer<String> htmlLazyInitializer = new LazyInitializer<String>() {
        @Override
        protected String initialize() throws ConcurrentException {
            try {
                ResourceScriptSource source = new ResourceScriptSource(new ClassPathResource("static/taskQueue.html"));
                return source.getScriptAsString();
            } catch (Exception e){
                logger.warn("加载taskQueue.html报错", e);
            }
            return "<html><body>加载页面失败</body></html>";
        }
    };

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        try {
            writer.write(htmlLazyInitializer.get());
        } catch (ConcurrentException e) {
            writer.write("");
        }
        writer.flush();
        writer.close();
    }
}
